package secret.hehe.com.secret.Activity;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONObject;

import secret.hehe.com.secret.R;
import secret.hehe.com.secret.Util.Util;

import static secret.hehe.com.secret.Util.Util.destroyWebView;
import static secret.hehe.com.secret.Util.Util.doDelete;
import static secret.hehe.com.secret.Util.Util.doInsert;
import static secret.hehe.com.secret.Util.Util.doSelect;
import static secret.hehe.com.secret.Util.Util.doUpdate;
import static secret.hehe.com.secret.Util.Util.startWebView;


public class MessageActivity extends AppCompatActivity {

    private String webUrl="file:///android_asset/html/Message.html";
    private WebView webView;
    private String userId;
    private String sendId;
    private String nickname="";
    private String eid="0";
    private int hasHidden=0;
    private int isHidden=0;
    private String result="";
    private JSONObject mailInfo;
    private String jsonString;
    private AlertDialog loading;
    private int from = 1;
    private int isCollect = 0;
    private int canClick=1;
    Util util = new Util();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        Intent intent = getIntent();
        //接收数据
        try {
            userId=(String) intent.getSerializableExtra("userId");
            if(userId==null)userId="0";
            eid=(String) intent.getSerializableExtra("eid");
            from=(int) intent.getSerializableExtra("from");
        }catch (Exception e){
            e.printStackTrace();
        }
        //防止变量杀死
        if (savedInstanceState != null) {
            try {
                userId = savedInstanceState.getString("userId");
                eid = savedInstanceState.getString("eid");
                from = savedInstanceState.getInt("from");
                canClick = savedInstanceState.getInt("canClick");
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //获取邮件信息
        String where = "eid="+eid;
        JSONArray jsonArray = doSelect("message",where,MessageActivity.this);
        JSONObject jsonObject=(JSONObject) jsonArray.opt(0);
        //是否为收藏
        where += " and userid='"+userId+"'";
        String collect = doSelect("collection",where,MessageActivity.this).toString();
        if(collect.equals("[]")){
            isCollect=0;
        }else{
            isCollect=1;
        }

        //处理信息
        mailInfo = jsonObject;
        try {
            String recvid = jsonObject.getString("recvid");
            hasHidden = mailInfo.getInt("ishidden");
            sendId = mailInfo.getString("sendid");
            if(userId.equals(recvid)){
                jsonObject.put("issend",0);
                JSONArray messageData = new JSONArray();
                messageData.put(jsonObject);
                doUpdate("message",messageData,getApplicationContext());
            }
            result="{\"data\":"+jsonArray.toString()+"}";
        }catch (Exception e){
            e.printStackTrace();
        }

        //有联系人的情况加入昵称
        try{
            String addressWhere = "user1='"+userId+"' and user2='"+sendId+"' and isscreen=0";
            JSONArray addressResult = doSelect("address",addressWhere,getApplicationContext());
            JSONObject address = (JSONObject)addressResult.opt(0);
            nickname = address.getString("nickname");
        }catch (Exception e){
            e.printStackTrace();
        }


        webView=new WebView(getApplicationContext());
        RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.message_context);
        startWebView(webView,webUrl,relativeLayout);
        webView.addJavascriptInterface(this, "android");

        Handler x = new Handler();
        x.postDelayed(new loadMessage(), 200);

        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_message, menu);
        //对方是否为联系人
        String where = "user1='"+userId+"' and user2='"+sendId+"' and isscreen=0";
        String contact = doSelect("address",where,getApplicationContext()).toString();
        MenuItem item = menu.getItem(0);
        if(contact.equals("[]")){

        }else{
            item.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish(); // back button
                return true;
            case R.id.add_contact:{//添加联系人
                try {
                    Intent intent = new Intent(MessageActivity.this, AddContactActivity.class);
                    intent.putExtra("sendId",userId);
                    intent.putExtra("recvId",sendId);
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
                return true;
            }
            case R.id.message_hidden: {
                if(hasHidden==1){//有隐秘信息
                    if(isHidden==0){//普通信息转至隐秘信息
                        final EditText et = new EditText(this);
                        et.setInputType(InputType.TYPE_CLASS_NUMBER);
                        InputFilter[] filters = {new InputFilter.LengthFilter(4)};
                        et.setFilters(filters);

                        new AlertDialog.Builder(this).setTitle("输入密码")
                                .setView(et)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String params = "eid=" + eid
                                                +"&&keybody=" +et.getText().toString();
                                        Util.postThread pwdThread = util.new postThread("/email/checkkeybody",getApplicationContext(),params,handler,1);
                                        pwdThread.start();
                                        loading = new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                                                .setMessage("确认中")//设置显示的内容
                                                .setCancelable(false)
                                                .show();
                                        return;
                                    }
                                }).setNegativeButton("取消", null).show();
                    }else {//隐秘信息转至普通信息
                        changeVersion();
                    }
                }else{//无隐藏信息
                    Toast.makeText(MessageActivity.this, "该邮件无隐秘信息", Toast.LENGTH_SHORT).show();
                }
                //refresh(result);
                return true;
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //保存变量
        super.onSaveInstanceState(outState);
        outState.putString("userId", userId);
        outState.putString("eid", eid);
        outState.putInt("from", from);
        outState.putInt("canClick", canClick);
    }

    @Override
    protected void onDestroy(){

        destroyWebView(webView);
        super.onDestroy();
    }
    @Override
    public void finish(){
        Intent intent = new Intent();
        setResult(1002,intent);
        super.finish();
    }

    Handler handler = new Handler() {
        //相应接受数据
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                //确认邮件密码
                canClick=1;
                try{
                    if(loading!=null){
                        loading.dismiss();
                        loading=null;
                    }
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){
                        //密码正确
                        Toast.makeText(MessageActivity.this, "密码正确", Toast.LENGTH_SHORT).show();
                        isHidden=1;
                        changeVersion();
                    }else{
                        //密码错误
                        Toast.makeText(MessageActivity.this, "密码错误", Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 2) {
                //进入回收站
                canClick=1;
                if(loading!=null){
                    loading.dismiss();
                    loading=null;
                }
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){
                        //成功
                        Toast.makeText(MessageActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                        mailInfo.put("isbin",1);
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.put(mailInfo);
                        doUpdate("message",jsonArray,getApplicationContext());
                        finish();
                    }else{
                        //失败
                        String message = jsonObject.getString("message");
                        Toast.makeText(MessageActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 3) {
                //删除邮件
                canClick=1;
                if(loading!=null){
                    loading.dismiss();
                    loading=null;
                }
                try{
                    jsonString = msg.obj.toString();
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int code = jsonObject.getInt("code");
                    if(code==200){
                        //成功
                        Toast.makeText(MessageActivity.this, "操作成功", Toast.LENGTH_SHORT).show();
                        mailInfo.put("isdel",1);
                        JSONArray jsonArray = new JSONArray();
                        jsonArray.put(mailInfo);
                        doUpdate("message",jsonArray,getApplicationContext());
                        finish();
                    }else{
                        //失败
                        String message = jsonObject.getString("message");
                        Toast.makeText(MessageActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (msg.what == 4) {
                canClick=1;
                change_collect();
            }
            if (msg.what == 0) {
                canClick=1;
                if(loading!=null){
                    loading.dismiss();
                    loading=null;
                }
                Toast.makeText(MessageActivity.this, "无网络或访问服务器出错", Toast.LENGTH_SHORT).show();
            }
        }
    };

    public void changeVersion() {         //调用js切换内容
        webView.loadUrl("javascript:change_ver()");
    }

    public void change_collect() {         //调用js切换内容
        webView.loadUrl("javascript:change_collect()");
    }

    public void refresh(String result) {         //调用js切换内容
        webView.loadUrl("javascript:window.refresh("+result+")");
    }

    public void refresh_nickname(String nickname) {         //调用js切换内容
        webView.loadUrl("javascript:refresh_nickname(\""+nickname+"\")");
    }

    @JavascriptInterface
    public void collect() {//收藏邮件
        if(isCollect==0){
            new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                    .setMessage("收藏此邮件")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            JSONObject collection = new JSONObject();
                            try{
                                collection.put("userid",userId);
                                collection.put("eid",eid);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                            JSONArray jsonArray = new JSONArray();
                            jsonArray.put(collection);
                            doInsert("collection",jsonArray,getApplicationContext());
                            Toast.makeText(getApplicationContext(), "已收藏", Toast.LENGTH_SHORT).show();
                            isCollect=1;
                            handler.sendEmptyMessage(4);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }else{
            new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                    .setMessage("取消收藏")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            String where = "userid="+userId+" and eid="+eid;
                            doDelete("collection",where,getApplicationContext());
                            Toast.makeText(getApplicationContext(), "已取消收藏", Toast.LENGTH_SHORT).show();
                            isCollect=0;
                            handler.sendEmptyMessage(4);
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }
    }
    @JavascriptInterface
    public void toSend() {//回复邮件
        if(canClick==1){
            canClick=0;
            try {
                Intent intent = new Intent(MessageActivity.this, SendActivity.class);
                intent.putExtra("recvId",sendId);
                canClick=1;
                startActivityForResult(intent,1001);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }
        }

    }
    @JavascriptInterface
    public void delMessage() {//删除邮件
        if(from==0){
            //从回收站来
            new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                    .setMessage("是否删除邮件")//设置显示的内容
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            String params = "userid="+userId
                                    +"&&eid[eid]="+eid;
                            Util.postThread delThread = util.new postThread("/email/delEmail",getApplicationContext(),params,handler,3);
                            delThread.start();
                            loading = new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                                    .setMessage("删除中")//设置显示的内容
                                    .setCancelable(false)
                                    .show();
                            return;
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        }else{
            //从别的地方
            new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                    .setMessage("放入回收站还是直接删除邮件")//设置显示的内容
                    .setPositiveButton("放入回收站", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            String params = "userid="+userId
                                    +"&&eid[eid]="+eid;
                            Util.postThread delThread = util.new postThread("/email/recycleEmail",getApplicationContext(),params,handler,2);
                            delThread.start();
                            loading = new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                                    .setMessage("操作中")//设置显示的内容
                                    .setCancelable(false)
                                    .show();
                            return;
                        }
                    })
                    .setNegativeButton("删除邮件", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            String params = "userid="+userId
                                    +"&&eid[eid]="+eid;
                            Util.postThread delThread = util.new postThread("/email/delEmail",getApplicationContext(),params,handler,3);
                            delThread.start();
                            loading = new AlertDialog.Builder(MessageActivity.this).setTitle("提示")//设置对话框标题
                                    .setMessage("删除中")//设置显示的内容
                                    .setCancelable(false)
                                    .show();
                            return;
                        }
                    })
                    .setNeutralButton("取消", null)
                    .show();
        }
    }

    @JavascriptInterface
    public void watchPicture(String path){
        if(canClick==1){
            canClick=0;
            //Android6.0后读写sd卡权限需要动态申请
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //申请WRITE_EXTERNAL_STORAGE权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        2000);
                canClick=1;
            }else{
                try {
                    Intent intent = new Intent(MessageActivity.this, PictureActivity.class);
                    intent.putExtra("userId",userId);
                    intent.putExtra("eid",eid);
                    intent.putExtra("path",path);
                    startActivity(intent);
                    canClick=1;
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @JavascriptInterface
    public String getResult(){
        return result;
    }

    @JavascriptInterface
    public int getisCollect(){
        return isCollect;
    }

    class loadMessage implements Runnable {
        public void run() {
            refresh(result);
            refresh_nickname(nickname);
        }

    }
}
